<template>
  <div class="page">
    <el-card class="box-card top-box-card">
      <el-form>
        <el-form-item label="标题">
          <el-input v-model="articleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="articleForm.desc"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <!-- TODO: 封面设置-->
          <el-input></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <!-- TODO: 标签设置-->
          <el-input></el-input>
        </el-form-item>
        <div class="btn-wrapper">
          <el-button v-if="!articleForm.publish" @click="handlePublish" type="success">发布</el-button>
          <el-button @click="handleSave" type="primary">保存</el-button>
        </div>
      </el-form>
    </el-card>
    <div class="md-editor-wrapper">
      <v-md-editor v-model="articleForm.content" height="720px"></v-md-editor>
    </div>

    <!-- <el-card class="box-card md-editor-wrapper" :body-style="{ padding: 0 }">
      
    </el-card> -->
  </div>
</template>

<script>
import api from '@/api/index'
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
  name: 'ArticleEditorView',
  components: {
  },
  props: {
    id: String
  },
  data() {
    return {
      articleForm: {
        _id: '',
        title: '',
        desc: '',
        coverUrl: '',
        content: '',
        publish: false,
        createDate: '',
        publishDate: '',
        lastEditDate: '',
        tags: [],
        // category: {},
      },
      // newArticleData: {
      //   _id: '',
      //   title: 'Untitled',
      //   desc: '',
      //   coverUrl: '',
      //   content: '',
      //   publish: false,
      //   createDate: '',
      //   publishDate: '',
      //   lastEditDate: '',
      //   tags: [],
      //   category: null,
      // },
      isChange: false,
    }
  },
  mounted() {
    this.loadArticle()
  },
  async beforeUpdate() {
    console.log('beforeUpdate')
    // console.log('this.isChange:', this.isChange)

    if (this.id == this.articleForm._id) {
      return
    }

    //防止当前文章没保存但用户又点击了"发布文章"按钮时不执行beforeRouteLeave()提示保存的问题
    if (this.isChange) {
      // showSaveMessage = false 表示close MessageBox
      if (!await this.showSaveMessage()) {
        return false //close不执行任何操作
      }
    }

    this.loadArticle()
  },
  async beforeRouteLeave() {
    console.log("beforeRouteLeave")
    console.log('this.isChange:', this.isChange)
    if (this.isChange) {
      return await this.showSaveMessage()
    }
  },
  watch: {
    articleForm: {
      deep: true,
      handler() {
        console.log('in watch articleForm')
        this.isChange = true
      }
    },
    text() {
      console.log("text:", this.text)
    }
  },
  methods: {
    loadArticle() {
      if (!this.id) {
        console.log('No article id')
        return
      }

      console.log('load article')
      api.article.getById(this.id).then((result) => {
        const article = result.data.article
        Object.keys(this.articleForm).forEach(key => {
          this.articleForm[key] = article[key]
        })

        // this.isChange被watch，需要等待页面更新后再设置this.isChange=false
        this.$nextTick(() => { this.isChange = false })
      }).catch((err) => {
        console.error("api.article.getById() err:", err)
      })
    },
    handlePublish() {
      // 发布

      // 保存修改
      api.article.changeArticle(this.articleForm._id, this.articleForm)
        .then(() => {
          // 设置为发布
          api.article.setPublish(this.articleForm._id)
            .then(() => {
              this.articleForm.publish = true
              this.$nextTick(() => { this.isChange = false })
              ElMessage.success('发布成功')
            })
        })

    },
    handleSave() {
      // 保存
      api.article.changeArticle(this.articleForm._id, this.articleForm).then(() => {
        this.isChange = false
        ElMessage.success('保存成功')
      })
    },
    async showSaveMessage() {
      return await ElMessageBox.confirm(
        '文件尚未保存，是否保存？',
        '提示',
        {
          distinguishCancelAndClose: true,  // 区分“取消”和“关闭”
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          type: 'info',
        })
        .then(() => {
          this.handleSave()
          return true
        })
        .catch((action) => {
          if (action === 'cancel') {
            console.log('cancel save')
            return true
          } else {
            console.log('close')
            return false  //取消页面跳转
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.top-box-card {
  margin-bottom: 18px;
}

.btn-wrapper {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

.md-editor-wrapper {
  width: 1200px;
  overflow: hidden;

  &:deep(.v-md-editor) {
    border-radius: 12px;
    box-shadow: 0px 2px 6px rgba(0, 0, 0, .1);
  }

  &:deep(.v-md-editor__editor-wrapper) {
    border-bottom-left-radius: 12px;
  }
}
</style>
